<template>
<div class="container">
    <el-row :span = "24">
        <el-col :span="5">
            <div class="container">
                <h3>组织架构</h3>
                <div style="margin-top:10px;font-size:14px;cursor:pointer;" @click="all">{{sjname}}({{num}}人)</div>
                <el-tree
					style="margin-top:10px;"
                    @node-click="handleNodeClick"
                    default-expand-all
                    :data="data"
                    :props="customProps">
                </el-tree>
            </div>
        </el-col>
        <el-col :span="18" style="margin-left:10px;" v-if="isShow">
             <div class="container">
                <h3>{{bumen}}</h3>
                <el-button style="margin-top:20px;" v-show="check3" v-if="ifshow" @click="clickedit">编辑</el-button>
                <el-button @click="zuzhi_del" v-show="check3" v-if="ifshow" style="margin-top:20px;">删除</el-button>
                <el-button v-if="threeshow" v-show="check3" @click="addedlowercontent" style="margin-top:20px;">添加下级</el-button>
                <div style="height:1px; background:#ebeff5;margin-top:20px;"></div>
                <el-row style="margin-top:20px;">
                    <el-col :span="7">
                        <el-input style="border-radius: 0 5px 5px 0" placeholder="请输入关键词" v-model="searchName">
                            <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            <el-button slot="append" @click="handleSearch">搜索</el-button>
                        </el-input>
                    </el-col>
                    <el-button style="float:right; margin-right: 10px" @click="download">模板下载</el-button>
                    <el-upload
                        class="upload-daoru"
                        ref="upload"
                        :action="action"
                        :on-change="uploadonchange"
                        accept=".xlsx,.xls"
                        :show-file-list='false'
                        :auto-upload="false">
                        <el-button slot="trigger" size="small">导入模板</el-button>
                    </el-upload>
                    <el-button type="primary" @click="addstaff" style="float:right; margin-right:10px;" v-if="!check">添加员工</el-button>
                </el-row>

                <el-table
                    :data="tableData"
                    border
                    style="margin-top:20px;"
                    ref="multipleTable"
                    header-cell-class-name="table-header">
                    <el-table-column prop="name" sortable label="姓名"></el-table-column>
                    <el-table-column prop="phone" sortable label="手机号"></el-table-column>
                    <el-table-column prop="department" sortable label="部门"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
							<div v-if="scope.row.checked">
                            <el-button
                                type="text"
                                v-if="!check1"
                                @click="handleEdit(scope.$index, scope.row)"
                            >编辑</el-button>
                            <el-button type="text">
                                <el-dropdown style="color: #409EFF; font-size:12px">
                                    <span class="el-dropdown-link">
                                        更多
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-show="!check5"
                                                v-if="state == scope.row.locked"
                                                @click="disabled(scope.$index, scope.row)"
                                                style="color: #666"
                                            >禁用</el-button>
                                        </el-dropdown-item>
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-show="!check4"
                                                v-if="state == scope.row.locked?false:true"
                                                @click="start(scope.$index, scope.row)"
                                                style="color: #666"
                                            >启用</el-button>
                                        </el-dropdown-item>
                                        <el-dropdown-item>
											<el-button
												type="text"
												v-show="!check6"
												@click="handleApartment(scope.$index, scope.row)"
											>调部门</el-button>
                                            <!-- <el-button
                                                type="text"
                                                v-show="check6"
                                                @click="handleDelete(scope.$index, scope.row)"
                                            >删除</el-button> -->
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </el-button>
							</div>
                        </template>
                    </el-table-column>
                </el-table>
                 <el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" @current-change="handleCurrentChange" :total="total" style="margin-top:20px"></el-pagination>

                </div>
        </el-col>
    </el-row>
	<el-dialog title="选择部门" :visible.sync="addeddialog1" customClass="customWidth">
		<div style="margin-top:10px;font-size:14px;cursor:pointer;" @click="all">{{sjname}}</div>
	    <el-tree
	    	style="margin-top:10px;"
	        @node-click="handleNodeClick1"
	        default-expand-all
	        :data="data"
			:highlight-current="true"
	        :props="customProps">
	    </el-tree>
	    <div slot="footer" class="dialog-footer">
	        <el-button @click="addeddialog1 = false">取 消</el-button>
	        <el-button type="primary" @click="apartment">确 定</el-button>
	    </div>
	</el-dialog>
    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
        <el-form :model="form" style="margin-left:100px;">
            <el-form-item label="部门名称">
                <el-input v-model="bumen" autocomplete="off" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="上级部门">
                <el-input v-model="shangjibumen" autocomplete="off" disabled="disabled" style="width:300px;"></el-input>
                <!-- <el-cascader :props="props" v-model="shangji" @change="ele" style="width:300px;"></el-cascader> -->
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit_sure">确 定</el-button>
        </div>
    </el-dialog>
    <el-dialog title="添加下级" :visible.sync="addeddialog">
        <el-form :model="form" style="margin-left:100px;">
            <el-form-item label="部门名称">
                <el-input v-model="form.name" autocomplete="off" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="上级部门">
                <el-input v-model="bumen" autocomplete="off" disabled="disabled" style="width:300px;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addeddialog = false">取 消</el-button>
            <el-button type="primary" @click="addlower">确 定</el-button>
        </div>
    </el-dialog>
</div>

</template>

<script>
    import {staffuser_daoru,staff_update,staff_getfindById,staff,company_findById,staff_findById,staffuser_update,staff_save,staff_delete,staff_getId,staffuser_findByList,staffuser_delete,staffuser_findByAll,user_locked,template_importUser,temmplate_toUser} from '@/request/api'
    export default {
        inject:['reload'],
        data() {
            return {
				addeddialog1:false,
                ifshow:false,
                action:"",
                check:true,//添加员工
                check1:true,//编辑
                check2:true,//删除
                check3:true,
                check4:true,//启用
                check5:true,//禁用
				check6:true,
                shangjibumen:'',
                threeshow:true,
                editid:'',
                lianjiid:'',
                options:[],
                shangjiid:[],
                data:[
                    {
                        id:'',
                        label:'',
                        children:[]
                    }
                ],
                shangji:'',
                total:1,
                currentPage:1,
                pagesize:10,
                state:false,
                bumenname:'',
                addeddialog:false,
                dialogFormVisible:false,
                bumen:'',
                searchName: '',
                defaultProps:{
                    children:'',
                    label:'label'
                },
                activeName: '1',
                tableData: [],
                form:{
                    name:'',
                    parentId:'',
                },
                editlist:{
                    name:'',
                    parentId:''
                },
                boxCode:'',
                boxCode1:'',

                level:'',
                isShow:true,
                delid:'',
                departmentId:'',
                customProps:{
                    label:'name',
                    children:'children',
                    id:'id'
                },
                shid:'',
                sjname:'',
                num:'',
				details:{}
            };
        },
        created(){

        },
        mounted(){
            this.init();
            this.init1();
            this.getnum();
            this.judgmentAuthority();
        },
        methods: {
			handleNodeClick1(ele,node,data){
				this.details.departmentId = ele.id
			},
			handleApartment(index,row){
				this.details = row
				this.addeddialog1 = true
			},
			apartment(){
				let formdata = new FormData()
				this.details.jobtime = new Date(this.details.jobtime)
				for(var a in this.details){
				    if(this.details[a] == null || this.details[a] == "null"){
				        this.details[a] = ""
				        formdata.append(a,'')
				    }else{
				        formdata.append(a,this.details[a])
				    }
				}
				staffuser_update(formdata).then((res)=>{
					this.$notify({
					    title: '提示',
					    message: '调整部门成功',
					    type: 'success'
					});
					this.addeddialog1 = false
					this.init()
				})
			},
            download(){
                 const companyId =  localStorage.getItem('companyId')
                 // console.log(companyId,'114')
                //  window.location.href = "http://" + window.location.host + "/template/toUser?"+companyId;
                //  window.location.href = "http://grove.cpzsyun.com:81/api" + "/plant/template/toCraft?appId=002&companyId=" + companyId;
                //  window.location.href = "http://grove.cpzsyun.com:81/api" + "/plant/template/toCraft?appId=002&companyId=" + companyId;
                // window.location.href = "http://grove.cpzsyun.com:81/api" + "/plant/template/toUser?appId=002&companyId=" + companyId
                window.location.href = "http://grove.cpzsyun.com:81/api" + "/plant/template/toUser?appId=002&companyId=" + companyId
				// temmplate_toUser("").then((res)=>{

				// })
            },
            uploadonchange(file) {
                let formData = new FormData();
                formData.append('file', file.raw);
                let config = {
                    headers:{'Content-Type':'multipart/form-data'}
                };
                template_importUser(formData).then((res) =>{
                    if (res.code == 200) {
                        this.$notify({
                            title: '操作成功',
                            message: '导入成功',
                            type: 'success'
                        });
                        this.init()
                    } else{
                        this.$notify.error({
                            title: '操作失败',
                            message: '导入失败',
                            type: 'error'
                        });
                    }
                })
            },
            all(){
                this.bumen = this.sjname
                this.ifshow = false
                let data = {
                    page:this.currentPage,
                }
                staffuser_findByList(data).then((res)=>{
                    this.tableData = res.rows

					res.rows.forEach(v => {
						v.checked = true
					});
					res.companyCount.checked = false
					this.tableData.unshift(res.companyCount)
					this.total = res.total + 1
                    var _this = this
                    for (let i = 0; i < this.tableData.length; i++) {
                        if(this.tableData[i].state == 0){
                            _this.tableData[i].stateful = "启用"
                        }else{
                            _this.tableData[i].stateful = "禁用"
                        }

                    }
                })

            },
            clickedit(){
                this.dialogFormVisible = true
                // this.shangjiid = this.lianjiid
            },
            clickget(ele){
                // console.log(ele)
            },
            init1(){
                var id = localStorage.getItem("companyId")
                company_findById(id).then((res)=>{
                    this.bumen = res.data.abbreviation
                    this.departmentId = res.data.id
                    this.sjid = res.data.id
                    this.sjname = res.data.abbreviation
                    staffuser_findByAll("").then((res)=>{
                        this.data = res.data
                    })
                })
            },

            ele(ele){

                var arr = ""
                for (let i = 0; i < this.shangji.length; i++) {
                    arr = this.shangji[i]
                }
                this.shangji = arr
            },
            start(index,row){
                this.$confirm('确定启用该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
					let data = {
						id:row.id,
						locked:false
					}
                    user_locked(data).then(res=>{
                        this.$notify({
                            title: '操作成功',
                            message: '启用成功',
                            type: 'success'
                        });
                        this.init()
                    })
                });
            },
            disabled(index,row){
                this.$confirm('确定禁用该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let data = {
                    	id:row.id,
                    	locked:true
                    }
                    user_locked(data).then(res=>{
                        this.$notify({
                            title: '操作成功',
                            message: '禁用成功',
                            type: 'success'
                        });
                        this.init()
                    })
                });
            },
            init(){
                var id = localStorage.getItem("companyId")
                if(this.delid == id){
                    this.departmentId = ""
                }else{
                    this.departmentId = this.delid
                }
                let data = {
                    page:this.currentPage,
                    departmentId:this.departmentId,
                    query:this.searchName
                }
                staffuser_findByList(data).then((res)=>{
                    this.tableData = res.rows
                    this.total = res.total
					res.rows.forEach(v => {
						v.checked = true
					});
					if(this.departmentId == id || this.departmentId == ""){
						res.companyCount.checked = false
						this.tableData.unshift(res.companyCount)
						this.total = this.total + 1
					}

                    var _this = this
                    for (let i = 0; i < this.tableData.length; i++) {
                        if(this.tableData[i].state == 0){
                            _this.tableData[i].stateful = "启用"
                        }else{
                            _this.tableData[i].stateful = "禁用"
                        }

                    }
                })
            },
            getnum(){
                var id = localStorage.getItem("companyId")
                if(this.delid == id){
                    this.departmentId = ""
                }else{
                    this.departmentId = this.delid
                }
                let data = {
                    page:this.currentPage,
                    departmentId:this.departmentId,
                    query:this.searchName
                }
                staffuser_findByList(data).then((res)=>{

                    this.num = res.total

                })
            },
            handleSearch(){
                this.currentPage = 1
                this.init()
            },
            submit_sure(){
                // var arr = ""
                // for (let i = 0; i < this.shangjiid.length; i++) {
                //     arr = this.shangjiid[i]
                // }
                // this.editlist.parentId = arr
                var id = localStorage.getItem("companyId")
                if(this.editlist.parentId == id){
                    var sid = ""
                }else{
                    if(list.parentId == ""){
                    this.$notify({
                        title: '提示',
                        message: '上级部门不能为空',
                        type: 'success'
                    });
                    return false
                }
                    var sid = this.editlist.parentId
                }
                let list = {
                    companyId:id,
                    id:this.editid,
                    name:this.bumen,
                    parentId:sid
                }

                if(list.name == ""){
                    this.$notify({
                        title: '提示',
                        message: '部门名称',
                        type: 'success'
                    });
                    return false
                }
                staff_update(list).then((res)=>{
                    this.$notify({
                        title: '操作成功',
                        message: '编辑成功',
                        type: 'success'
                    });
                    this.dialogFormVisible = false
                    this.init();
                    this.init1();
                    this.getnum();
                    this.judgmentAuthority();
                })
            },
            addedlowercontent(){
                if(this.bumen == ""){
                    this.$notify({
                        title: '提示',
                        message: '请先选择部门',
                        type: 'info'
                    });
                }else{
                    this.addeddialog = true
                }

            },
            zuzhi_del(){
                if(this.bumen == ""){
                    this.$notify({
                        title: '提示',
                        message: '请先选择部门',
                        type: 'info',

                    });
                }else{
                    this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        staff_delete(this.delid).then((res)=>{
                            this.$notify({
                                title: '操作成功',
                                message: '删除成功',
                                type: 'success'
                            });
                            // this.reload()

                        })
                    }).catch(() => {

                    });
                }
            },
            addlower(){
                staff_save(this.form).then((res)=>{
                    this.$notify({
                    title: '操作成功',
                    message: '保存成功',
                    type: 'success'
                });
                    this.addeddialog = false
                    this.init();
                    this.init1();
                    this.getnum();
                    this.judgmentAuthority();
                })
            },
            // 调用接口
            getcase(){

            },
            handleNodeClick(ele,node,data){
                this.ifshow = true
                // console.log(data)
                var id = localStorage.getItem("companyId")
                if(node.level == "3"){
                    this.threeshow = false
                }else{
                    this.threeshow = true
                }


                if(node.level == "1"){
                    this.shangjibumen = this.sjname
                    this.editlist.parentId = id
                }else{
                    this.editlist.parentId = ele.parentId
                    staff_getfindById(this.editlist.parentId).then((res)=>{
                        this.shangjibumen = res.data.name
                    })
                }

                // this.level = node.level
                this.editid = ele.id
                this.delid = ele.id
                this.bumen = ele.name
                var arr = []

                // console.log(ele)
                // console.log(node)
                if(ele.id == id){
                }else{
                    arr[0] = ele.companyId
                    if(ele.parentId != "null" && ele.parentId != "" && ele.parentId != null){
                        arr[1] = ele.parentId
                    }else{

                    }
                }

                this.shangjiid = arr
                var id = localStorage.getItem("companyId")
                if(ele.id == id){
                    this.form.parentId = ""
                }else{
                    this.form.parentId = ele.id
                }
                this.init()
            },
            addstaff(){
                this.$router.push({
                    path:'/staffsManagement/addedstaff',
                    query:{
                        sid:this.editlist.parentId
                    }
                })
            },
            handleEdit(index,row){
                this.$router.push({
                    path:'/staffsManagement/addedstaff',
                    query:{
                        id:row.id
                    }
                })
            },
            handleCurrentChange(val){
                this.currentPage = val
                this.init()
            },


            handleDelete(index,row){
                this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    staffuser_delete(row.id).then((res)=>{
                        this.$notify({
                            title: '操作成功',
                            message: '删除成功',
                            type: 'success'
                        });
                        this.init()
                    })


                });
            },

            //判定操作按钮显示
            judgmentAuthority() {
                var type = JSON.parse(localStorage.getItem('panduanzhuangtai'));
                type.map((item1) => {
                    if (item1.name == '员工管理' && item1.children != null) {
                        for (var i = 0; i < item1.children.length; i++) {
                            if (item1.children[i].name == '新增') this.check = false;
                            if (item1.children[i].name == '编辑') this.check1 = false;
                            if (item1.children[i].name == '启用') this.check4 = false;
                            if (item1.children[i].name == '禁用') this.check5 = false;
                            if (item1.children[i].name == '调部门') this.check6 = false;
                        }
                    }
                });
            }
        }
    }
</script>

<style scoped lang="less">
/deep/.el-upload--text{
    line-height: initial;
}
/deep/.upload-daoru{
    background: #eee;
    .el-upload{
        border: none;
        width: auto;
        height: auto;
        border-radius: 0;
        float: right;
        margin-right: 10px
    }
}
/* .el-row{ margin-bottom: 20px;} */
 .el-pagination{
    text-align: center;
}
.input-with-select .el-input-group__prepend {
background-color: #fff;
}
.el-input--small .el-input__inner{
    border-radius: 5px 0 0 5px !important;
    border-right: none;
}
.customWidth{
		width:30%;
	}
</style>
